using MediatR;
using Microsoft.EntityFrameworkCore;
using NSwag.AspNetCore;
using ProxyServer.EntityFrameworkCore;
using ProxyServer.Yarp;

namespace ProxyServer;

public record ProxyConfigRemovedEevet(AppProxyConfig Config) : INotification
{
    public Guid Id { get; set; } = Config.SnapshotId;
    public DateTimeOffset Removed { get; set; } = DateTimeOffset.UtcNow;
}

public sealed class ProxyConfigRemovedEevetHandler: INotificationHandler<ProxyConfigRemovedEevet>
{
    private readonly ILogger<ProxyConfigRemovedEevetHandler> _logger;
    private readonly IServiceProvider _serviceProvider;

    public ProxyConfigRemovedEevetHandler(ILogger<ProxyConfigRemovedEevetHandler> logger, IServiceProvider serviceProvider)
    {
        _logger = logger;
        _serviceProvider = serviceProvider;
    }

    public async Task Handle(ProxyConfigRemovedEevet notification, CancellationToken cancellationToken)
    {
        _logger.LogInformation("Proxy configuration removed with ID: {Id} at {Removed}", notification.Id, notification.Removed);
        
        using var scope = _serviceProvider.CreateAsyncScope();
        using var _dbContext = scope.ServiceProvider.GetRequiredService<AppDbContext>();

        await _dbContext.Snapshots
        .Where(x => x.Id == notification.Id)
        .ExecuteUpdateAsync(x => x.SetProperty(y => y.RemovedAt, notification.Removed), cancellationToken: cancellationToken);
    }
}